<?php

/**
 * Project controller.
 *
 * This file will render views from views/pages/
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('CakeEmail', 'Network/Email');
App::uses('AppController', 'Controller');

/**
 * Static content controller
 *
 * Override this controller by placing a copy in controllers directory of an application
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class UsersController extends AppController {

	public $components = array(
		'Cookie'
	);

	/**
	 * Controller name
	 *
	 * @var string
	 */
	public $name = 'Users';

	/**
	 * This controller does not use a model
	 *
	 * @var array
	 */
	public $uses = array();

	public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow(array('signup', 'verify', 'forgot', 'reset_password'));
	}

	/**
	 * Displays a view
	 *
	 * @param mixed What page to display
	 * @return void
	 */
	public function login() {
		$user = AuthComponent::user();
		if($user['role_id']){
		$this->redirect('/admin/users');
		}else{
		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
				if (!empty($this->data['User']['keep_signed'])) {
					$this->Cookie->write('keep_signed', $this->data['User']['username'], '+7 days');
				}
				$this->User->updateLastActivity($this->Auth->user('id'));
				return $this->redirect($this->Auth->redirect());
			} else {
				$this->setFlash(__('Username or password is incorrect'));
			}
		} else {
			$username = $this->Cookie->read('keep_signed');
			$this->set('username', $username);
		}
		}
	}
	public function admin_add() {
	}
	public function admin_index() {
		if (!empty($this->data)) {
			switch ($this->data['Paginate']['task']) {
				case 'add':
					$this->Dashboard->redirect(array('action' => 'add'));
			}
		}
		$users = $this->User->find('all', array('recursive' => -1, 'conditions' => array(
				'not' => array('username' => 'admin')
		)));
		$this->set(compact('users'));
	}

	public function admin_import() {
		if (!empty($this->data)) {
			include APP . 'Vendor' . DS . 'PHPExcel' . DS . 'IOFactory.php';
			$objPHPExcel = PHPExcel_IOFactory::load($this->data['Import']['file']['tmp_name']);
			$count = $success = 0;

			unset($this->User->validate['username']);
			foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
				$highestRow = $worksheet->getHighestRow();
				for ($row = 1; $row <= $highestRow; ++$row) {
					$data = array(
						'booking' => trim($worksheet->getCellByColumnAndRow(0, $row)->getValue()),
						'last_name' => trim($worksheet->getCellByColumnAndRow(1, $row)->getValue()),
						'first_name' => trim($worksheet->getCellByColumnAndRow(2, $row)->getValue()),
						'email' => trim($worksheet->getCellByColumnAndRow(3, $row)->getValue()),
						'amount' => trim($worksheet->getCellByColumnAndRow(4, $row)->getValue())
					);
					if (!array_filter($data)) {
						continue;
					}
					$count++;
					$user = $this->User->find('first', array(
						'recursive' => -1,
						'conditions' => array('booking' => $data['booking']),
						'fields' => 'id'
					));
					if ($user) {
						$this->User->id = $user['User']['id'];
					} else {
						
						$data += array(
							'password' => '123456',
							'tos' => true,
							'email_verified' => true
						);
					}
					$this->User->create();
					if ($this->User->save($data)) {
						$success++;
					}
				}
			}
			$this->setFlash(__('The %s/%s user has been imported', $success, $count), 'success');
			$this->Dashboard->redirect(array('action' => 'index'), true, true);
		}
	}

	public function admin_delete($id = null) {
		if ($this->User->delete($id)) {
			$this->setFlash(__('The user has been deleted'), 'success');
		} else {
			$this->setFlash(__('The user count not be deleted'));
		}
		$this->Dashboard->redirect(array('action' => 'index'), true, true);
	}

	public function admin_config() {
		$contents = ClassRegistry::init('Content')->find('list');
		if ($this->request->is('post')) {
			Configure::write('AppConfig', $this->data['AppConfig']);
			file_put_contents(APP . 'Config' . DS . 'config.php', '<?php $config=' . var_export(array(
						'AppConfig' => $this->data['AppConfig']
							), true) . ';');
			$this->setFlash(__('The setting has been saved'), 'success');
			$this->Dashboard->redirect(array('action' => 'index'), true, true);
		} else {
			$this->data = array('AppConfig' => Configure::read('AppConfig'));
		}
		$this->set(compact('contents'));
	}

	public function logout() {
		$this->Auth->logout();
		$this->redirect('/');
	}

	public function signup() {
		if ($this->Auth->user()) {
			$this->setFlash(__('You are already registered and logged in!'));
			$this->redirect(array(
				'controller' => 'projects'
			));
		}

		if (!empty($this->request->data)) {
			$user = $this->User->register($this->request->data);
			if ($user !== false) {
				$this->_sendVerificationEmail($this->User->data);
				$this->setFlash(__('Your account has been created. You should receive an e-mail shortly
					to authenticate your account. Once validated you will be able to login.'), 'success');
				$this->redirect(array('action' => 'login'));
			} else {
				unset($this->request->data['User']['password']);
				unset($this->request->data['User']['temppassword']);
				$this->setFlash(__('Your account could not be created. Please, try again.'));
			}
		}
	}

	public function forgot() {
		$options = array(
			'subject' => __('Password Reset'),
			'template' => 'password_reset_request',
			'emailFormat' => CakeEmail::MESSAGE_TEXT,
			'layout' => 'default'
		);
		if (!empty($this->request->data)) {
			$user = $this->User->passwordReset($this->request->data);
			if (!empty($user)) {
				$Email = new CakeEmail('default');
				$Email->to($user['User']['email'])
						->emailFormat($options['emailFormat'])
						->subject($options['subject'])
						->template($options['template'], $options['layout'])
						->viewVars(array(
							'model' => 'User',
							'user' => $this->User->data,
							'token' => $this->User->data['User']['password_token']))
						->send();
				$this->setFlash(__('You should receive an email with further instructions shortly'), 'success');
				$this->redirect(array('action' => 'login'));
			} else {
				$this->setFlash(__('No user was found with that email.'));
				$this->redirect($this->referer('/'));
			}
		}
	}

	public function verify($token = null) {
		try {
			$this->User->verifyEmail($token);
			$this->setFlash(__('Your e-mail has been validated!'), 'success');
			return $this->redirect(array('action' => 'login'));
		} catch (RuntimeException $e) {
			$this->setFlash($e->getMessage());
			return $this->redirect('/');
		}
	}

	public function reset_password($token) {
		$user = $this->User->checkPasswordToken($token);
		if (empty($user)) {
			$this->setFlash(__('Invalid password reset token, try again.'));
			$this->redirect(array('action' => 'forgot'));
		}

		if (!empty($this->request->data) && $this->User->resetPassword(Set::merge($user, $this->request->data))) {
			$this->setFlash(__('Password changed, you can now login with your new password.'), 'success');
			$this->Session->delete('Auth.redirect');
			$this->redirect($this->Auth->loginAction);
		}
	}

	/**
	 * Sends the verification email
	 *
	 * This method is protected and not private so that classes that inherit this
	 * controller can override this method to change the varification mail sending
	 * in any possible way.
	 *
	 * @param string $to Receiver email address
	 * @param array $options EmailComponent options
	 * @return boolean Success
	 */
	protected function _sendVerificationEmail($userData, $options = array()) {
		$defaults = array(
			'subject' => __('Account verification'),
			'template' => 'account_verification',
			'layout' => 'default',
			'emailFormat' => CakeEmail::MESSAGE_TEXT
		);

		$options = array_merge($defaults, $options);

		$Email = new CakeEmail('default');
		$Email->to($userData['User']['email'])
				->emailFormat($options['emailFormat'])
				->subject($options['subject'])
				->template($options['template'], $options['layout'])
				->viewVars(array(
					'model' => 'User',
					'user' => $userData
				))
				->send();
	}

}
